package com.tinyengine.it.controller.endpoint;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.tinyengine.it.common.base.Result;
import com.tinyengine.it.common.utils.JavaDataType;
import com.tinyengine.it.model.dto.generator.ResponseBodyDto;
import com.tinyengine.it.model.entity.ApiEndpoints;
import com.tinyengine.it.model.vo.ApiEndpointVo;
import com.tinyengine.it.service.endpoint.ApiDirectoryService;
import com.tinyengine.it.service.endpoint.ApiEndpointsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.connector.Response;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/endpoints/api")
@Tag(name = "接口定义-详情")
@RequiredArgsConstructor
public class ApiEndpointsController {

    private final ApiEndpointsService apiEndpointsService;
    private final ApiDirectoryService apiDirectoryService;

    @Operation(summary = "新增及更新",
            responses = {@ApiResponse(responseCode = "200", description = "返回信息",
                    content = @Content(mediaType = "application/json",
                            schema = @Schema(implementation = Result.class))),
                    @ApiResponse(responseCode = "400", description = "请求失败")}
    )
    //@SystemControllerLog(description = "获取项目、服务、分组TREE")
    @PostMapping("/addAndUpdate")
    public Result addAndUpdate(@RequestBody @Validated ApiEndpointVo apiEndpointVo) {

        List<ResponseBodyDto> responseBodyDtos1 = JSON.parseArray(JSON.toJSONString(apiEndpointVo.getResponseBody().get("example")), ResponseBodyDto.class);

        ResponseBodyDto responseBodyDto = responseBodyDtos1.stream()
                .filter(item -> item.getExpect() != null && Response.SC_OK == item.getExpect().getCode())
                .findFirst().get();
        Integer shipVoId = responseBodyDto.getShipVoId();
        String dataType = responseBodyDto.getDataType();
        if (StrUtil.isBlank(dataType)) {
            throw new RuntimeException("需要选择接口返回类型!");
        }
        if (!dataType.toUpperCase().equals(JavaDataType.String.getValue()) && ObjUtil.isNull(shipVoId)) {
            throw new RuntimeException("接口返回类型需要关联对应的VO!");
        }

        ApiEndpoints apiEndpoints = BeanUtil.copyProperties(apiEndpointVo, ApiEndpoints.class);

        //Integer directoryId = apiEndpoints.getDirectoryId();
        //ApiGatewayService apiDirectory = apiDirectoryService.getServiceInfoByEndPointId(directoryId);

        //apiEndpoints.setPathReqFull(apiDirectory.getServiceEn() + "/" + apiEndpoints.getPathReq());

        apiEndpointsService.saveOrUpdate(apiEndpoints);
        return Result.success(apiEndpoints.getId());
    }


    @Operation(summary = "根据ID删除",
            parameters = {
                    @Parameter(name = "id", description = "ID")},
            responses = {@ApiResponse(responseCode = "200", description = "返回信息",
                    content = @Content(mediaType = "application/json",
                            schema = @Schema(implementation = Result.class))),
                    @ApiResponse(responseCode = "400", description = "请求失败")}
    )
    //@SystemControllerLog(description = "获取项目、服务、分组TREE")
    @GetMapping("/deleteById/{id}")
    public Result deleteEndpointInfoById(@Valid @PathVariable Integer id) {
        apiEndpointsService.removeById(id);
        return Result.success();
    }

    @Operation(summary = "根据ID获取详情",
            responses = {@ApiResponse(responseCode = "200", description = "返回信息",
                    content = @Content(mediaType = "application/json",
                            schema = @Schema(implementation = ApiEndpointVo.class))),
                    @ApiResponse(responseCode = "400", description = "请求失败")}
    )
    @GetMapping("/getDetailById/{id}")
    public Result getDetailById(@Valid @PathVariable Integer id) {
        ApiEndpoints apiEndpoints = apiEndpointsService.getById(id);
        return Result.success(BeanUtil.copyProperties(apiEndpoints, ApiEndpointVo.class));
    }


}
